<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>

          <a-col :span="24">
            <a-form-model-item label="班级" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="classId">
              <a-select v-model="model.classId" placeholder="请选择班级"
                        :getPopupContainer="(target) => target.parentNode">
                <a-select-option v-for="item in classList" :key="item.value">{{ item.label }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="科目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="subjectId">
              <a-select v-model="model.subjectId" placeholder="请选择科目"
                        :getPopupContainer="(target) => target.parentNode" @change="handleSubjectChange">
                <a-select-option v-for="item in subjectList" :key="item.value">{{ item.label }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="任课教师" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teacherId">
              <a-select v-model="model.teacherId" placeholder="请选择教师"
                        :getPopupContainer="(target) => target.parentNode">
                <a-select-option v-for="item in teacherList" :key="item.value">{{ item.label }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="学年" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teacherId">
                <j-dict-select-tag v-model='model.schoolYearId' placeholder='请选择学年'
                                   dictCode='cou_school_year,school_year_name,id' />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="学期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teacherId">
              <j-dict-select-tag v-model='model.semesterId' placeholder='请选择学期'
                                   dictCode='cou_semester,semester_name,id' />
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="教学楼（或场地）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="buildingId">
              <j-dict-select-tag v-model='model.buildingId' placeholder='教学楼（或场地）'
                                 dictCode='fac_building,building_name,id' @change='handleBuildingChange' />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="教室场地(默认班级所在教室)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="classroomId">
              <a-select v-model="model.classroomId" placeholder="教室场地(默认班级所在教室)"
                        :getPopupContainer="(target) => target.parentNode">
                <a-select-option v-for="item in classroomList" :key="item.value">{{ item.label }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import {
  getAllClass,
  getSubjectList,
  getTeacherList,
  queryTeacherListBySubject,
  getBuildingDataList,
  getCoursePlanDataList,
  getClassroomList
} from '@api/commonAPI'

export default {
  name: 'RelClassSubjectTeacherForm',
  components: {},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        subjectId: [
          { required: true, message: '请输入科目id!' }
        ]
      },
      url: {
        add: '/rel_class_subject_teacher/relClassSubjectTeacher/add',
        edit: '/rel_class_subject_teacher/relClassSubjectTeacher/edit',
        queryById: '/rel_class_subject_teacher/relClassSubjectTeacher/queryById'
      },
      classList: [],
      teacherList: [],
      subjectList: [],
      classroomList: [],
      buildingDataList: [],
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    this.initList()
  },
  methods: {
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.model.buildingId = this.model.classroomId_dictText;
      this.handleBuildingChange();
      this.visible = true
    },
    async getBuildingData(){
      let res = await getBuildingDataList()
      if (res.success) {
        this.buildingDataList = []
        res.result.forEach(item => {
          this.buildingDataList.push({
            label: item.buildingName,
            value: item.id
          })
        })
      }
    },
    submitForm() {
      const that = this
      // 触发表单验证
      if (localStorage.length > 0) {
        let localData = JSON.parse(localStorage.getItem('pro__Login_Userinfo'))
        let tenantId = localData.value.tenantId
        this.model.tenantId = tenantId
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          this.classList.forEach(item=>{
            if(item.value == this.model.classId){
              this.model.className = item.label
            }
          })
          httpAction(httpurl, this.model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }

      })
    },
    async initList() {
      // let res = await getTeacherList()
      // if (res.code === 200) {
      //   this.teacherList = []
      //   res.result.forEach(item => {
      //     this.teacherList.push({
      //       label: item.teacherName,
      //       value: item.teacherId
      //     })
      //   })
      // }

      let subjectList = await getSubjectList()
      if (subjectList.code === 200) {
        this.subjectList = []
        subjectList.result.forEach(item => {
          this.subjectList.push({
            label: item.subjectName,
            value: item.subjectId
          })
        })
      }

      let classesList = await getAllClass()
      if (classesList.code === 200) {
        this.classList = []
        classesList.result.forEach(item => {
          this.classList.push({
            label: item.className,
            value: item.id
          })
        })
      }
    },
    async handleSubjectChange() {
      let tenantId = ''
      if (localStorage.length > 0) {
        let localData = JSON.parse(localStorage.getItem('pro__Login_Userinfo'))
        tenantId = localData.value.tenantId
        this.model.tenantId = tenantId
      }
      let params = {
        tenantId: tenantId,
        subjectId: this.model.subjectId
      }
      let res = await queryTeacherListBySubject(params)
      if (res.success) {
        this.teacherList = []
        res.result.forEach(item => {
          this.teacherList.push({
            value: item.teacherId,
            label: item.teacherName
          })
        })
      }
    },

    async handleBuildingChange() {
      let params = {
        buildingId: this.model.buildingId
      }
      let res = await getClassroomList(params)
      if (res.success) {
        this.classroomList = []
        res.result.forEach(item => {
          this.classroomList.push({
            value: item.id,
            label: item.classroomName
          })
        })
      }
    }
  }
}
</script>